import React, { createRef, PureComponent } from 'react'
import { connect, history } from '@umijs/max'
import {
 Button, message, Popconfirm, Select,
} from 'antd'
import {
 BreadcrumbBar, InputSearch, ProTable, ProTableOperate, ProTableOptions, OSSyncComponentModal,
} from '@/components'
import styles from './index.less'

const menus = [{ name: '接口采集' }, { name: 'Http/Https' }]
const { OperateItem } = ProTableOperate
const { Option } = Select

@connect(({ httpsApi }) => ({ ...httpsApi }))
class HttpsApi extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: '任务名称',
          dataIndex: 'taskName',
          key: 'taskName',
          width: '12%',
        },
        {
          title: '请求方式',
          dataIndex: 'httpRequestMethod',
          key: 'httpRequestMethod',
          width: '8%',
        },
        {
          title: '接口地址',
          dataIndex: 'url',
          key: 'url',
          width: '18%',
        },
        {
          title: '目标端',
          dataIndex: 'storageTable',
          key: 'storageTable',
          width: '12%',
        },
        {
          title: '发布状态',
          dataIndex: 'taskStatus',
          key: 'taskStatus',
          width: '8%',
          render: (taskStatus) => (
            <>
              {
                taskStatus === 1 && (
                  <><i className="iconfont icon-daiban hu-blue" /> 待发布</>
                )
              }
              {
                taskStatus === 2 && (
                  // <><i className="iconfont icon-yunhangzhong_1 hu-green" /> 已发布</>
                  <><i style={{ color: '#43A047' }} className="iconfont icon-yifabu" /> 已发布</>
                )
              }
              {
                taskStatus === 4 && (
                  <><i className="iconfont icon-yunhangzhong_1 hu-blue" /> 运行中</>
                )
              }
              {
                taskStatus === 5 && (
                  <><i className="iconfont icon-chenggong hu-green" /> 成功</>
                )
              }
              {
                taskStatus === 6 && (
                  <><i className="iconfont icon-shibai1 hu-red" /> 失败</>
                )
              }
              {
                taskStatus === 7 && (
                  <><i className="iconfont icon-weiyunhang hu-blue" /> 停止</>
                )
              }
              {
                taskStatus === 9 && (
                  <><i className="iconfont icon-guidang hu-blue" /> 已归档</>
                )
              }
            </>
          ),
        },
        {
          title: '调度周期',
          dataIndex: 'cycle',
          key: 'cycle',
          width: '7%',
          render: (cycle) => (
            <>
              {cycle === 0 && '月'}
              {cycle === 1 && '周'}
              {cycle === 2 && '天'}
              {cycle === 3 && '小时'}
              {cycle === 4 && '分钟'}
            </>
          ),
        },
        {
          title: '发布时间',
          dataIndex: 'startTime',
          key: 'startTime',
          width: '12%',
        },
        // {
        //   title: '结束时间',
        //   dataIndex: 'endTime',
        //   key: 'endTime',
        //   width: '12%',
        // },
        {
          title: '创建人',
          dataIndex: 'createBy',
          key: 'createBy',
          width: '8%',
        },
        {
          title: '操作',
          key: 'action',
          render: (record) => {
            const {
              id, taskStatus, taskName, createBy,
            } = record
            return (
              <ProTableOptions>
                <span onClick={() => { history.push(`/dataIntegrate/apiGather/http-create?id=${id}&isView=view`) }}>查看</span>
                {
                  (taskStatus === 1 || taskStatus === 5 || taskStatus === 6 || null) && <span onClick={() => { history.push(`/dataIntegrate/apiGather/http-create?id=${id}`) }}>编辑</span>
                }
                {(taskStatus === 1 || taskStatus === 2 || taskStatus === 5 || taskStatus === 6 || null) && <span onClick={() => { this.handleOperateItem(id, 'reRun') }}>试运行</span>}
                {(taskStatus === 1 || null) && <span onClick={() => { this.handleOperateItem(id, 'publish') }}>发布</span>}
                {/* {(taskStatus === 4 || null) && <span onClick={() => { this.handleOperateItem(id, 'stop') }}>停止</span>} */}
                {(taskStatus === 2 || taskStatus === 5 || taskStatus === 6 || null) && <span onClick={() => { this.handleOperateItem(id, 'offline') }}>下线</span>}
                <span onClick={() => { history.push(`/dataIntegrate/apiGather/view-history?id=${id}&taskName=${taskName}&createBy=${createBy}&type=http`) }}>历史任务</span>
                {
                  (taskStatus !== 2 || taskStatus !== 4 || null) && (
                    <Popconfirm
                      title="确认要删除吗？"
                      onConfirm={() => { this.handleOperateItem(id, 'delete') }}
                      okText="确定"
                      cancelText="取消"
                    >
                      <span>删除</span>
                    </Popconfirm>
                  )
                }
                {process.env.APP_ENV === 'os' ? (
                  <span onClick={() => { this.onOSSync(record) }}>
                    同步
                  </span>
                ) : null}
              </ProTableOptions>
            )
          },
        },
      ],
      taskStatus: -1,
      downlined: 0,
      failed: 0,
      successed: 0,
      taskName: '',
      query: {
        taskStatus: -1,
      },
      forceUpdate: 0,
      osSyncVisible: false,
      osSynclabel: '',
      osSyncjobid: '',
    }
    this.tableRef = createRef()
  }

  componentDidMount() {
    this.initCensusData()
  }

  onOSSync = (record) => {
    this.setState({
      osSyncVisible: true,
      osSyncjobid: record.id,
      osSynclabel: record.taskName,
    })
  }

  initCensusData = () => {
    this.props.dispatch({
      type: 'httpsApi/queryGetOverview',
      cb: (data) => {
        const { downlined, failed, successed } = data || {}
        this.setState({
          downlined,
          failed,
          successed,
        })
      },
    })
  }

  fetchData = () => {
    const { taskStatus, taskName, query } = this.state
    this.tableRef?.current?.resetPageNum()
    const tempQuery = {}
    tempQuery.search = taskName
    tempQuery.taskStatus = taskStatus
    this.setState({
      query: {
        ...query,
        ...tempQuery,
      },
    })
  }

  // 操作
  handleOperateItem = (taskId, type) => {
    this.setState({
      loading: true,
    })

    let operateType = null
    switch (type) {
      case 'reRun':
        operateType = 'queryReRunTask'
        break
      case 'offline':
        operateType = 'queryDownlineTask'
        break
      case 'delete':
        operateType = 'queryDelete'
        break
      case 'publish':
        operateType = 'queryPublishTask'
        break
      case 'stop':
        operateType = 'queryStop'
        break
      default:
        operateType = ''
    }

    const paramsTemp = {}
    if (type === 'stop') {
      paramsTemp.logId = taskId
    } else {
      paramsTemp.taskId = taskId
    }

    this.props.dispatch({
      type: `httpsApi/${operateType}`,
      params: {
        ...paramsTemp,
      },
      cb: (res) => {
        const { msg, status } = res
        this.setState({
          loading: false,
        })
        if (status === 200) {
          message.success('操作成功')
          this.setState((prevState) => ({
            forceUpdate: prevState.forceUpdate + 1,
          }))
          this.initCensusData()
        } else {
          message.error(msg || '服务端错误')
        }
      },
    })
  }

  render() {
    const {
      columns, taskStatus, downlined, failed, successed, loading, query, forceUpdate, osSyncVisible, osSyncjobid, osSynclabel,
    } = this.state

    return (
      <div className={styles.page_content_with_breadcrumb}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.page_content}>
          <div className={styles.page_content_right}>
            <div className={styles.data_show}>
              <div className={styles.item}>
                <div><span className={styles.column}>待发布</span> <span className={styles.count}>{downlined}</span></div>
                <i className="iconfont-colour2 icon-yunhangzhong" />
              </div>
              <div className={styles.item}>
                <div><span className={styles.column}>成功</span> <span className={styles.count}>{successed}</span></div>
                <i className="iconfont-colour2 icon-chenggong_1" />
              </div>
              <div className={styles.item}>
                <div><span className={styles.column}>失败</span> <span className={styles.count}>{failed}</span></div>
                <i className="iconfont-colour2 icon-shibai_1" />
              </div>
            </div>
            <ProTableOperate style={{ marginBottom: 12 }}>
              <OperateItem>
                <span>任务状态</span>
                <Select
                  value={taskStatus}
                  onChange={(value) => {
                    this.setState({
                      taskStatus: value,
                    }, () => { this.fetchData() })
                  }}
                >
                  <Option key={-1} value={-1}>全部</Option>
                  <Option key={1} value={1}>待发布</Option>
                  <Option key={2} value={2}>已发布</Option>
                  {/* <Option key={4} value={4}>运行中</Option>
                  <Option key={5} value={5}>成功</Option>
                  <Option key={6} value={6}>失败</Option>
                  <Option key={7} value={7}>停止</Option>
                  <Option key={9} value={9}>已归档</Option> */}
                </Select>
              </OperateItem>
              <OperateItem align="left">
                <InputSearch
                  placeholder="请输入任务名称进行搜索"
                  onChange={(e) => {
                    this.setState({
                      taskName: e.target.value,
                    })
                  }}
                  onSearch={this.fetchData}
                />
              </OperateItem>
              <OperateItem itemType="btn">
                <Button type="primary" onClick={() => { history.push('/dataIntegrate/apiGather/http-create') }}>新建任务</Button>
              </OperateItem>
            </ProTableOperate>
            <ProTable
              ref={this.tableRef}
              loading={loading}
              key={forceUpdate}
              url="/api/v1/integration/api/http/getTaskList"
              query={query}
              rowKey="id" // key传递的是否有效，影响rowSelection的使用
              columns={columns}
            />
          </div>
        </div>
        <OSSyncComponentModal
          visible={osSyncVisible}
          onClose={() => this.setState({ osSyncVisible: false })}
          jobtype="4"
          jobid={osSyncjobid}
          label={osSynclabel}
        />
      </div>
    )
  }
}

export default HttpsApi
